package com.jishuo.base.controller;

import com.jishuo.base.annotation.UserAuthority;
import com.jishuo.base.bean.BaseResult;
import com.jishuo.base.bean.ErrorCodeEnum;
import com.jishuo.base.bean.vo.UserVO;
import com.jishuo.base.config.AppConfig;
import com.jishuo.base.service.UserService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.annotation.Resource;
import javax.servlet.http.HttpSession;

@Slf4j
@Controller
@RequestMapping(value = "/", name = "系统主页")
@UserAuthority
public class IndexController {
    @Resource
    private UserService userService;

    @Value("${application.app-name}")
    private String appName;
    @Value("${sys.login-captcha:on}")
    private String captcha;

    @RequestMapping(value = {"index", "index/{page}"}, name = "首页")
    public String index(@PathVariable(required = false) String page, HttpSession session, Model model) {
        model.addAttribute("appName", this.appName);
        model.addAttribute("captcha", this.captcha);
        return (page == null) ? "index" : page;
    }

    @ResponseBody
    @RequestMapping(value = "getLoginUser", name = "获得登录用户")
    public BaseResult getLoginUser(HttpSession session) {
        BaseResult ret = new BaseResult();
        UserVO user = (UserVO) session.getAttribute(AppConfig.LOGIN_USER_SESSION_KEY);
        if (user == null) {
            return new BaseResult(ErrorCodeEnum.NO_LOGIN);
        } else {
            ret.setData(user.getUserName());
            return ret;
        }
    }

    @ResponseBody
    @RequestMapping(value = "login", name = "登录")
    public BaseResult login(HttpSession session, UserVO user) {
        if (!"off".equals(this.captcha)) {
            String validateC = (String) session.getAttribute(AppConfig.CAPTCHA_SESSION_KEY);
            session.removeAttribute(AppConfig.CAPTCHA_SESSION_KEY);
            if (validateC == null || !validateC.equalsIgnoreCase(user.getViery())) {
                return new BaseResult(ErrorCodeEnum.CUSTOM_ERR.getCode(), "验证码错误");
            }
        }

        BaseResult ret = this.userService.login(user.getUserCode(), user.getUserPwd());
        if (ret.isSuccess()) {
            session.setAttribute(AppConfig.LOGIN_USER_SESSION_KEY, ret.getData());
            return new BaseResult();
        } else {
            return ret;
        }
    }

    @ResponseBody
    @RequestMapping(value = "logout", name = "登出")
    public BaseResult logout(HttpSession session, UserVO user) {
        session.removeAttribute(AppConfig.LOGIN_USER_SESSION_KEY);
        return new BaseResult();
    }
}
